package bookmanagementsystem.gui;

import bookmanagementsystem.dao.BookDAO;
import bookmanagementsystem.dao.BorrowingDAO;
import bookmanagementsystem.dao.ReturningDAO;
import bookmanagementsystem.model.Book;
import bookmanagementsystem.model.BorrowingRecord;
import bookmanagementsystem.model.ReturningRecord;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.util.List;

public class MainFrame extends JFrame {
    private JLabel welcomeLabel;
    // 用于图书查询、借阅、归还功能相关的组件
    private JTextField bookIDField;
    private JTextField bookNameField;
    private JTextField authorNameField;
    private JTextField quantityInLibraryField;
    private JTextField locationField;
    private JTextField authorNameQueryField;
    private JTextField bookNameQueryField;
    private JButton queryBookButton;
    private JButton borrowBookButton;
    private JButton returnBookButton;
    private JButton modifyPasswordButton;
    private JButton modifyPersonalInfoButton;
    private JButton queryBorrowingRecordsButton;
    private JButton queryReturningRecordsButton;
    private JList<String> bookList;
    // 用于存储当前登录用户的ID（通过LoginFrame传递过来）
    private String currentUserID;

    // 创建DAO对象，方便后续使用，避免在各个方法中重复创建
    private BookDAO bookDAO;
    private BorrowingDAO borrowingDAO;
    private ReturningDAO returningDAO;

    // 修改构造方法，接收从LoginFrame传递过来的用户ID
    public MainFrame(String userID) {
        this.currentUserID = userID;
        setTitle("图书管理系统 - 主界面");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化DAO对象
        bookDAO = new BookDAO();
        borrowingDAO = new BorrowingDAO();
        returningDAO = new ReturningDAO();

        initComponents();
        addComponentsToFrame();
        addActionListeners();
    }

    private void initComponents() {
        welcomeLabel = new JLabel("欢迎来到图书管理系统主界面！");
        bookIDField = new JTextField(40);
        bookNameField = new JTextField(40);
        authorNameField = new JTextField(40);
        quantityInLibraryField = new JTextField(40);
        locationField = new JTextField(40);
        queryBookButton = new JButton("查询图书");
        borrowBookButton = new JButton("借阅图书");
        returnBookButton = new JButton("归还图书");
        modifyPasswordButton = new JButton("修改密码");
        modifyPersonalInfoButton = new JButton("修改个人信息");
        queryBorrowingRecordsButton = new JButton("查询借书记录");
        queryReturningRecordsButton = new JButton("查询还书记录");
        authorNameQueryField = new JTextField(40);
        bookNameQueryField = new JTextField(40);

        // 用于初始的图书列表
        bookList = new JList<>();
    }

    private void addComponentsToFrame() {
        // 主面板，采用BorderLayout布局，划分不同功能区域
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 上部面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(welcomeLabel);

        // 图书查询相关输入框部分，单独一个面板，每行一个组件方便对齐，设置合适宽度确保显示完整
        JPanel queryInputPanel = new JPanel(null); // 使用绝对布局，便于手动设置组件位置和大小
        queryInputPanel.setPreferredSize(new Dimension(700, 150)); // 设置面板大小，可根据实际调整

        int x = 10;
        int y = 10;
        int labelWidth = 100;
        int textFieldWidth = 250;
        int verticalGap = 25;

        // 添加图书ID
        JLabel bookIDLabel = new JLabel("图书ID：");
        bookIDLabel.setBounds(x, y, labelWidth, 20);
        queryInputPanel.add(bookIDLabel);
        bookIDField.setBounds(x + labelWidth + 5, y, textFieldWidth, 20);
        queryInputPanel.add(bookIDField);
        y += verticalGap;

        // 添加图书名称
        JLabel bookNameQueryLabel = new JLabel("图书名称：");
        bookNameQueryLabel.setBounds(x, y, labelWidth, 20);
        queryInputPanel.add(bookNameQueryLabel);
        bookNameQueryField.setBounds(x + labelWidth + 5, y, textFieldWidth, 20);
        queryInputPanel.add(bookNameQueryField);
        y += verticalGap;

        // 添加作者
        JLabel authorNameLabel = new JLabel("作者：");
        authorNameLabel.setBounds(x, y, labelWidth, 20);
        queryInputPanel.add(authorNameLabel);
        authorNameField.setBounds(x + labelWidth + 5, y, textFieldWidth, 20);
        queryInputPanel.add(authorNameField);
        y += verticalGap;

        // 添加库存
        JLabel quantityInLibraryLabel = new JLabel("库存数量：");
        quantityInLibraryLabel.setBounds(x, y, labelWidth, 20);
        queryInputPanel.add(quantityInLibraryLabel);
        quantityInLibraryField.setBounds(x + labelWidth + 5, y, textFieldWidth, 20);
        queryInputPanel.add(quantityInLibraryField);
        y += verticalGap;

        // 添加位置
        JLabel locationLabel = new JLabel("存放位置：");
        locationLabel.setBounds(x, y, labelWidth, 20);
        queryInputPanel.add(locationLabel);
        locationField.setBounds(x + labelWidth + 5, y, textFieldWidth, 20);
        queryInputPanel.add(locationField);

        topPanel.add(queryInputPanel);

        // 中部面板，放置操作按钮
        JPanel middlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        // 借阅相关按钮
        JPanel borrowPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        borrowPanel.add(queryBookButton);
        borrowPanel.add(borrowBookButton);
        borrowPanel.add(returnBookButton);

        // 个人信息修改按钮
        JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        infoPanel.add(modifyPasswordButton);
        infoPanel.add(modifyPersonalInfoButton);

        // 记录查询
        JPanel recordPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        recordPanel.add(queryBorrowingRecordsButton);
        recordPanel.add(queryReturningRecordsButton);

        middlePanel.add(borrowPanel);
        middlePanel.add(infoPanel);
        middlePanel.add(recordPanel);

        // 下部面板，放置图书列表展示相关组件
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(new JLabel("图书列表："), BorderLayout.NORTH);
        bottomPanel.add(new JScrollPane(bookList), BorderLayout.CENTER);

        // 将各部分面板添加到主面板相应区域
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(middlePanel, BorderLayout.CENTER);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        getContentPane().add(mainPanel);
    }

    private void addActionListeners() {
        queryBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText().trim();
                String bookName = bookNameQueryField.getText().trim();

                Book book = null;

                // 如果图书ID不为空，则根据图书ID查询
                if (!bookID.isEmpty()) {
                    book = bookDAO.queryBookById(bookID);
                }

                // 如果图书ID为空且图书名称不为空，则根据图书名称查询
                if (book == null && !bookName.isEmpty()) {
                    book = bookDAO.queryBookByName(bookName);
                }

                if (book != null) {
                    // 打开新界面展示查询到的图书信息
                    BookQueryResultFrame bookQueryResultFrame = new BookQueryResultFrame(book);
                    bookQueryResultFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "未查询到该图书信息，请检查输入。");
                }
            }
        });

        borrowBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                BorrowingRecord borrowingRecord = borrowingDAO.queryBorrowingByUserAndBook(currentUserID, bookID);
                if (borrowingRecord != null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您已经借阅过此图书，无需再次借阅。");
                    return;
                }

                Book book = bookDAO.queryBookById(bookID);
                if (book == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "未查询到该图书ID对应的图书，请检查输入的图书ID是否正确。");
                    return;
                }
                if (book.getQuantityInLibrary() <= 0) {
                    JOptionPane.showMessageDialog(MainFrame.this, "该图书库存为零，无法借阅。");
                    return;
                }

                // 创建借阅记录，设置借阅时间和预计归还时间（这里假设借阅期限为30天）
                Timestamp borrowingTime = new Timestamp(System.currentTimeMillis());
                Timestamp expectedReturnTime = new Timestamp(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L);
                BorrowingRecord newBorrowingRecord = new BorrowingRecord(currentUserID, bookID, borrowingTime, expectedReturnTime);

                // 添加借阅记录到数据库
                if (borrowingDAO.addBorrowing(newBorrowingRecord)) {
                    // 更新图书库存数量
                    if (borrowingDAO.updateBookQuantityOnBorrow(bookID)) {
                        JOptionPane.showMessageDialog(MainFrame.this, "借阅图书成功！");
                        updateBookList();
                    } else {
                        JOptionPane.showMessageDialog(MainFrame.this, "借阅图书成功，但更新图书库存数量失败，请联系管理员，错误信息：更新库存操作未成功。");
                    }
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "借阅图书失败，请检查输入信息或联系管理员，错误信息：添加借阅记录到数据库失败。");
                }
            }
        });

        returnBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                BorrowingRecord borrowingRecord = borrowingDAO.queryBorrowingByUserAndBook(currentUserID, bookID);
                if (borrowingRecord == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您未借阅过此图书，无法归还。");
                    return;
                }

                Timestamp returningTime = new Timestamp(System.currentTimeMillis());
                ReturningRecord returningRecord = new ReturningRecord(currentUserID, bookID, returningTime);

                // 添加归还记录到数据库
                if (returningDAO.addReturning(returningRecord)) {
                    // 更新图书库存数量
                    if (borrowingDAO.updateBookQuantityOnReturn(bookID)) {
                        JOptionPane.showMessageDialog(MainFrame.this, "归还图书成功！");
                        updateBookList();
                    } else {
                        JOptionPane.showMessageDialog(MainFrame.this, "归还图书成功，但更新图书库存数量失败，请联系管理员，错误信息：更新库存操作未成功。");
                    }
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "归还图书失败，请检查输入信息或联系管理员，错误信息：添加归还记录到数据库失败。");
                }
            }
        });

        modifyPasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ModifyUserInfoFrame modifyUserInfoFrame = new ModifyUserInfoFrame(currentUserID);
                modifyUserInfoFrame.setVisible(true);
            }
        });

        modifyPersonalInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ModifyPersonalInfoFrame modifyPersonalInfoFrame = new ModifyPersonalInfoFrame(currentUserID);
                modifyPersonalInfoFrame.setVisible(true);
            }
        });

        queryBorrowingRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<BorrowingRecord> borrowingRecords = borrowingDAO.queryBorrowingRecordsByUser(currentUserID);
                if (borrowingRecords.isEmpty()) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您暂无借书记录。");
                } else {
                    // 打开新界面展示借书记录
                    BorrowingRecordsFrame borrowingRecordsFrame = new BorrowingRecordsFrame(borrowingRecords);
                    borrowingRecordsFrame.setVisible(true);
                }
            }
        });

        queryReturningRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<ReturningRecord> returningRecords = returningDAO.queryReturningRecordsByUser(currentUserID);
                if (returningRecords.isEmpty()) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您暂无还书记录。");
                } else {
                    // 打开新界面展示还书记录
                    ReturningRecordsFrame returningRecordsFrame = new ReturningRecordsFrame(returningRecords);
                    returningRecordsFrame.setVisible(true);
                }
            }
        });

        updateBookList();
    }

    private void updateBookList() {
        List<Book> books = bookDAO.queryAllBooks();
        String[] bookDescriptions = new String[books.size()];

        for (int i = 0; i < books.size(); i++) {
            bookDescriptions[i] = books.get(i).getBookID() + " - " + books.get(i).getBookName();
        }

        bookList.setListData(bookDescriptions); // 用数组更新JList
    }
}